<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>06_列表渲染_过滤与排序</title>
</head>
<body>
<!--
1. 列表过滤
2. 列表排序
-->

<div id="demo">
	<input type="text" v-model="searchName">
	<ul>
		<li v-for="(p, index) in filterPersons" :key="index">
			{{index}}--{{p.name}}--{{p.age}}
		</li>
	</ul>
	<div>
		<button @click="setOrderType(2)">年龄升序</button>
		<button @click="setOrderType(1)">年龄降序</button>
		<button @click="setOrderType(0)">原本顺序</button>
	</div>
</div>

<script type="text/javascript" src="../vue.js"></script>
<script type="text/javascript">
    new Vue({
        el: '#demo',
        data: {
            searchName: '',
            orderType: 0, // 0代表不排序, 1代表降序, 2代表升序
            persons: [
                {name: 'Tom', age:20},
                {name: 'Jack', age:17},
                {name: 'Bob', age:19},
                {name: 'Mary', age:16}
            ]
        },

        computed: {
            filterPersons () {
//        debugger
                // 取出相关数据
                const {searchName, persons, orderType} = this
                let arr = [...persons]
                // 过滤数组
                if(searchName.trim()) {
                    arr = persons.filter(p => p.name.indexOf(searchName)!==-1)
                }
                // 排序
                if(orderType) {
                    arr.sort(function (p1, p2) {
                        if(orderType===1) { // 降序
                            if(p1.age - p2.age>0){
                                console.log(p1.age+"大于"+p2.age+"调换位置")
                            }else if(p1.age - p2.age<0){
                                console.log(p1.age+"小于"+p2.age+"位置不变")
                            }else{
                                console.log(p1.age+"等于"+p2.age+"位置不变")
                            }
                            return p2.age-p1.age
                        } else { // 升序
                            return p1.age-p2.age
                        }
                    })
                }
                return arr
            }
        },

        methods: {
            setOrderType (orderType) {
                this.orderType = orderType
            }
        }
    })
</script>
</body>
</html>